package com.ff.javamonkey.test.ui;

import java.io.IOException;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ff.javamonkey.R;
import com.ff.javamonkey.bluetooth.BluetoothService;
import com.ff.javamonkey.xmodem.ZModem;

public class DeviceList extends Activity {
	// Debugging
	private static final String TAG = "BluetoothTestActivity";

	// Return Intent extra
	public static String EXTRA_DEVICE_ADDRESS = "device_address";

	// Member fields
	private BluetoothAdapter mBtAdapter;
	private ArrayAdapter<String> mPairedDevicesArrayAdapter;
	private ArrayAdapter<String> mNewDevicesArrayAdapter;
	// Name of the connected device
	private String mConnectedDeviceName = null;

	// Intent
	private static final int REQUEST_CONNECT_DEVICE = 1;
	private static final int REQUEST_ENABLE_BT = 2;

	// Unique UUID for this application? What's unique? What the hell is it?
	private static final UUID MY_UUID = UUID
			.fromString("00001101-0000-1000-8000-00805F9B34FB");

	// The connection rleated threads
	private ConnectThread mConnectThread;
	private BluetoothService mBtService = null;

	// Message identifier
	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;
	public static final int MESSAGE_WRITE_FILE = 6;
	public static final int MESSAGE_WRITE_FILE_FINISHED = 7;

	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(TAG, "DeviceList: +++ onCreate +++");
		setContentView(R.layout.device_list);

		// Get local Bluetooth adapter
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBtAdapter == null) {
			Toast.makeText(this, "Bluetooth is not available",
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}

//		if (!mBtAdapter.isEnabled()) {
//			Intent enableIntent = new Intent(
//					BluetoothAdapter.ACTION_REQUEST_ENABLE);
//			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
//		}
//
		Button scanButton = (Button) findViewById(R.id.button_scan);
		scanButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				doDiscovery();
				v.setVisibility(View.GONE);
			}
		});		
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.i(TAG, "DeviceList: onStart");
		if (!mBtAdapter.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		}
		else {
			if (mBtService == null) setupService();
		}
	}
	
	@Override
	public synchronized void onResume() {
		super.onResume();
		Log.i(TAG, "DeviceList: onResume");
		
		if (mBtService != null) {
			if (mBtService.getState() == BluetoothService.STATE_NONE) {
				mBtService.start();
			}
		}
		
		populateDeviceLists();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// Stop
		if (mBtService != null) mBtService.stop();
		Log.i(TAG, "DeviceList: onDestroy");
	}
	
	@Override
	public synchronized void onPause() {
		super.onPause();
		Log.i(TAG, "DeviceList: onPause");
	}
	
	@Override
	public void onStop() {
		super.onStop();
		Log.i(TAG, "DeviceList: onStop");
	}
	
	private void setupService() {
		Log.i(TAG, "DeviceList: setupService()");
		
		mBtService = new BluetoothService(DeviceList.this, mHandler);
	}

	private void doDiscovery() {
		setProgressBarIndeterminateVisibility(true);
		setTitle("Scanning...");
		findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
		if (mBtAdapter.isDiscovering()) {
			mBtAdapter.cancelDiscovery();
		}
		mBtAdapter.startDiscovery();
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth enabled.
				setupService();
			} else {
				return;
			}
			break;
		case REQUEST_CONNECT_DEVICE:
			if (resultCode == Activity.RESULT_OK) {
				String address = data.getExtras().getString(
						DeviceList.EXTRA_DEVICE_ADDRESS);
				BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
				
			}
		}
	}

	public synchronized void connected(BluetoothSocket socket,
			BluetoothDevice device) {
		Log.i(TAG, "DeviceList: Do we get called?");
	}
	
	private void populateDeviceLists() {
		mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.device_name);
		mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.device_name);

		ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
		pairedListView.setAdapter(mPairedDevicesArrayAdapter);
		pairedListView.setOnItemClickListener(mDeviceClickListener);

		ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
		newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
		newDevicesListView.setOnItemClickListener(mDeviceClickListener);

		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		this.registerReceiver(mReceiver, filter);

		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		this.registerReceiver(mReceiver, filter);

		// get bonded devices
		Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

		if (pairedDevices.size() > 0) {
			findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
			for (BluetoothDevice device : pairedDevices) {
				mPairedDevicesArrayAdapter.add(device.getName() + "\n"
						+ device.getAddress());
			}
		} else {
			String noDevices = "None paired";
			mPairedDevicesArrayAdapter.add(noDevices);
		}
	}

	// The on-click listener for all devices in the ListViews
	private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
			// Cancel discovery because it's costly and we're about to connect
			mBtAdapter.cancelDiscovery();

			// Get the device MAC address, which is the last 17 chars in the
			// View
			String info = ((TextView) v).getText().toString();
			String address = info.substring(info.length() - 17);

			BluetoothDevice device = mBtAdapter.getRemoteDevice(address);

			mBtService.connect(device);
			
//			mConnectThread = new ConnectThread(device);
//			mConnectThread.start();
		}
	};

	// The BroadcastReceiver that listens for discovered devices and
	// changes the title when discovery is finished
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			// When discovery finds a device
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// Get the BluetoothDevice object from the Intent
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				// If it's already paired, skip it, because it's been listed
				// already
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					mNewDevicesArrayAdapter.add(device.getName() + "\n"
							+ device.getAddress());
				}
				// When discovery is finished, change the Activity title
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				setProgressBarIndeterminateVisibility(false);
				setTitle("Select Device");
				if (mNewDevicesArrayAdapter.getCount() == 0) {
					String noDevices = "None Found";
					mNewDevicesArrayAdapter.add(noDevices);
				}
			}
		}
	};

	private class ConnectThread extends Thread {
		private final BluetoothSocket mmSocket;
		private final BluetoothDevice mmDevice;

		public ConnectThread(BluetoothDevice device) {
			mmDevice = device;
			BluetoothSocket tmp = null;
			try {
				Log.i(TAG,
						"DeviceList: " + device.getName() + ": "
								+ device.getAddress());
				tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
				Log.i(TAG, "DeviceList: After tmp: " + device.getName() + ": "
						+ device.getAddress());
			} catch (IOException ioe) {
				Log.i(TAG, "DeviceList: Create ConnectThread failed");
			}
			mmSocket = tmp;
		}

		public void run() {
			setName("ConnectThread");
			mBtAdapter.cancelDiscovery();
			try {
				Log.i(TAG, "DeviceList: Beginning connection");
				mmSocket.connect();
				Log.i(TAG, "DeviceList: Passed connection");
				// writeFile("/sdcard/AngryBirds_1.3.5.apk");
				writeFile("/sdcard/image2211.pdf");
			} catch (IOException ioe) {
				Log.e(TAG,
						"DeviceList: Connection failed to : "
								+ mmDevice.getName(), ioe);
				try {
					mmSocket.close();
				} catch (IOException ioe2) {
					Log.e(TAG,
							"DeviceList: unable to close() socket during connection failure",
							ioe2);
				}
				return;
			}
		}

		public void writeFile(Object file) {
			Log.i(TAG, "DeviceList: Wow, it is actually went through");
			ZModem zmodem;
			try {
				zmodem = new ZModem(file.toString(),
						mmSocket.getOutputStream(), mmSocket.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
				Log.i(TAG, "DeviceList: Failed miserably you asshole");
			}
		}
	}

	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_STATE_CHANGE:
				switch (msg.arg1) {
				case BluetoothService.STATE_CONNECTED:
					Toast.makeText(getApplicationContext(),
							"Connected to " + mConnectedDeviceName,
							Toast.LENGTH_LONG).show();
					break;
				case BluetoothService.STATE_CONNECTING:
					Toast.makeText(getApplicationContext(), "Connecting...",
							Toast.LENGTH_SHORT).show();
					break;
				case BluetoothService.STATE_LISTEN:
				case BluetoothService.STATE_NONE:
					Toast.makeText(getApplicationContext(), "Listen or None",
							Toast.LENGTH_SHORT).show();
					break;
				}
				break;
			case MESSAGE_DEVICE_NAME:
				mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
				Toast.makeText(getApplicationContext(),
						"Connected to " + mConnectedDeviceName,
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
}
